package com.whfc.common.util;

import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Base64;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/10/15 9:59
 */
public class Base64Util {
    private static final Logger logger = LoggerFactory.getLogger(Base64Util.class);
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    public static String encodeToString(String src) {
        byte[] srcBytes = src.getBytes(DEFAULT_CHARSET);
        byte[] dstBytes = Base64.getEncoder().encode(srcBytes);
        return new String(dstBytes, DEFAULT_CHARSET);
    }

    public static String encodeToString(byte[] src) {
        byte[] dstBytes = Base64.getEncoder().encode(src);
        return new String(dstBytes, DEFAULT_CHARSET);
    }

    public static byte[] encode(String src) {
        byte[] srcBytes = src.getBytes(DEFAULT_CHARSET);
        byte[] dstBytes = Base64.getEncoder().encode(srcBytes);
        return dstBytes;
    }

    public static byte[] encode(byte[] src) {
        byte[] dstBytes = Base64.getEncoder().encode(src);
        return dstBytes;
    }

    public static String decodeToString(String src) {
        byte[] srcBytes = src.getBytes(DEFAULT_CHARSET);
        byte[] dstBytes = Base64.getDecoder().decode(srcBytes);
        return new String(dstBytes, DEFAULT_CHARSET);
    }

    public static String decodeToString(byte[] src) {
        byte[] dstBytes = Base64.getDecoder().decode(src);
        return new String(dstBytes, DEFAULT_CHARSET);
    }

    public static byte[] decode(String src) {
        byte[] srcBytes = src.getBytes(DEFAULT_CHARSET);
        byte[] dstBytes = Base64.getDecoder().decode(srcBytes);
        return dstBytes;
    }

    public static byte[] decode(byte[] src) {
        byte[] dstBytes = Base64.getDecoder().decode(src);
        return dstBytes;
    }

    /**
     * 由图片地址获取base64Str
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String getUrlImageToBase64(String url) {
        if (url == null || "".equals(url.trim())) {
            return "";
        }
        String result = "";
        try {
            URL u = new URL(url);
            // 打开图片路径
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            // 设置请求方式为GET
            conn.setRequestMethod("GET");
            // 设置超时响应时间为5秒
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            // 通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = inStream.read(buff, 0, 1024)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] in2b = swapStream.toByteArray();
            // 读取图片字节数组
            inStream.close();
            // 返回Base64编码过的字节数组字符串
            result = Base64Util.encodeToString(in2b);
        } catch (Exception e) {
            logger.error("由图片url获取base64Str失败", e.getMessage());
        }
        return result;
    }

    /**
     * 由图片地址获取输入流
     *
     * @param url
     * @return
     */
    public static InputStream getInputStream(String url) {
        if (url == null || "".equals(url.trim())) {
            return null;
        }
        InputStream inStream = null;
        try {
            URL u = new URL(url);
            // 打开图片路径
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            // 设置请求方式为GET
            conn.setRequestMethod("GET");
            // 设置超时响应时间为5秒
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            // 通过输入流获取图片数据
            inStream = conn.getInputStream();

        } catch (Exception e) {
            logger.error("由图片url获取inputStream失败", e.getMessage());
        }
        return inStream;
    }


    public static void main(String[] args) {

        String str1 = "https://file.whfciot.com/ms/pro/emp/img/2020051419276.png";
        String base64Str = Base64Util.encodeToString(str1);
        String str2 = Base64Util.decodeToString(base64Str);

        System.out.println(str1);
        System.out.println(base64Str);
        System.out.println(str2);
        System.out.println(getUrlImageToBase64(str1));
        Assert.assertEquals(str1, str2);
    }
}
